package com.shixihub.data;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Optional;

/**
 * @author LiShixi 2021/7/2 2:39 下午
 */
public class AppDataManager {
    public static final String APP_DAT_FILE = "app.dat";
    public AppDataEntity appDataEntity = new AppDataEntity();

    public Optional<File> checkDataFile() {
        return checkFile(APP_DAT_FILE);
    }

    public Optional<File> checkFile(String path) {
        //final URL resource = AppDataManager.class.getResource("/" + path);
        //if (Objects.isNull(resource)) {
        //    return Optional.empty();
        //}
        final String file = getDataFileDir() + File.separator + path;
        final Path path1 = Paths.get(file).toAbsolutePath();
        if (Files.exists(path1)) {
            return Optional.of(path1.toFile());
        }
        return Optional.empty();
    }

    /**
     * 恢复数据
     * @return
     */
    public AppDataEntity restore() {
        try {
            final Optional<File> dataFile = checkDataFile();
            if (dataFile.isPresent()) {
                final File absoluteFile = dataFile.get().getAbsoluteFile();
                try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(absoluteFile))) {
                    appDataEntity = (AppDataEntity) in.readObject();
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return appDataEntity;
    }

    /**
     * 保存数据对象
     *
     * @return 文件修改时间
     */
    public String store(AppDataEntity appDataEntity) {
        try {
            final String name = getDataFileDir() + APP_DAT_FILE;
            System.out.println("dat file path at  = " + name);
            final Path dir = Paths.get(getDataFileDir());
            if (!Files.exists(dir)) {
                Files.createDirectory(dir);
            }
            try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(name))) {
                out.writeObject(appDataEntity);
                out.flush();
            }
            return Files.getLastModifiedTime(Paths.get(name).toAbsolutePath()).toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String getDataFileDir() {
        final URL resource = getClass().getResource("/");
        String root = "";
        if (Objects.isNull(resource)) {
            root = System.getProperty("user.home") + File.separator + "jump-trans" + File.separator;
        }
        return root;
    }

    public AppDataEntity getAppDataEntity() {
        return appDataEntity;
    }

    public void setAppDataEntity(AppDataEntity appDataEntity) {
        this.appDataEntity = appDataEntity;
    }
}
